const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()
exports.main = async (event, context) => {
	const wxContext = cloud.getWXContext()
	let staff = await db.collection('staff').field({
		group_id: true,
	}).where({
		_openid: wxContext.OPENID,
		shop_id: event.shop_id,
	}).get()
	if (staff.data.length == 0) {
		return {
			code: 20003,
			msg: '您无权进行此操作'
		}
	}
	staff = staff.data[0]

	if (staff.group_id !=1) {
		//仅创始人可操作员工管理
		return {
			code: 20003,
			msg: '您无权进行此操作'
		}
	}
	let count = await db.collection('staff').where({
		shop_id:event.shop_id,
		_openid:event._openid,
	}).count()
	if(count.total>0){
		return {
			code: 200,
			msg: '已在员工列表中',
		}
	}
	console.log(event)
	let data = {
		_openid :event._openid,
		create_time:new Date(),
		update_time:new Date(),
		group_id:2,
		shop_id:event.shop_id
	}
	let add = await db.collection('staff').add({
		data
	})
	if (add.errMsg == 'collection.add:ok') {
		return {
			code: 200,
			msg: '员工增加成功',
		}
	}else{
		return {
			code: 20006,
			msg: '员工增加失败',
		}
	}

}